package com.gtxc.kotlinmvvm.utlis;

import android.content.Context;
import android.content.res.AssetManager;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Map;

/**
 * ClassName JSONUtils
 * Description JSONUtils
 * Author sr
 * Date 2019/3/27 16:34
 */
public class JSONUtils {
    private static Gson gson;

    private JSONUtils() {
    }

    static {
        GsonBuilder gb = new GsonBuilder();
        gb.setDateFormat("yyyy-MM-dd HH:mm:ss");
        gson = gb.create();
    }

    public static final String toJson(Object object, Type typeOfSrc) {
        return gson.toJson(object, typeOfSrc);
    }

    public static final String toJson(Object object) {
        return gson.toJson(object);
    }

    public static final <T> T fromJson(final String json, Class<T> clazz) {
        if (json == null) return null;
        return gson.fromJson(json, clazz);
    }

    public static final <T> T fromJson(final String json, Type t) {
        return gson.fromJson(json, t);
    }

    public static final Map<String, Object> fromJson(final String json) {
        return fromJson(json, Map.class);
    }

    /**
     * 专门解析返回的为[]格式的数组数据
     *
     * @param json
     * @param cls
     * @param <T>
     * @return
     */

    public static <T> ArrayList<T> fromJsonList(String json, Class<T> cls) {
        if (json == null) return null;
        ArrayList<T> mList = new ArrayList<T>();

        JsonArray array = new JsonParser().parse(json).getAsJsonArray();

        for (final JsonElement elem : array) {

            mList.add(gson.fromJson(elem, cls));

        }

        return mList;

    }

    public static String getJson(Context context, String fileName) {

        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

}
